module.exports = (sequelize, DataTypes) => {
  const DiaryTag = sequelize.define('DiaryTag', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    diary_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'diaries',
        key: 'id'
      }
    },
    tag_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'tags',
        key: 'id'
      }
    }
  }, {
    tableName: 'diary_tags',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: false, // 关联表不需要更新时间
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [
      {
        fields: ['diary_id']
      },
      {
        fields: ['tag_id']
      },
      {
        unique: true,
        fields: ['diary_id', 'tag_id'],
        name: 'unique_diary_tag'
      }
    ]
  });

  DiaryTag.associate = (models) => {
    // 关联表属于日记
    DiaryTag.belongsTo(models.Diary, {
      foreignKey: 'diary_id',
      as: 'diary',
      onDelete: 'CASCADE'
    });

    // 关联表属于标签
    DiaryTag.belongsTo(models.Tag, {
      foreignKey: 'tag_id',
      as: 'tag',
      onDelete: 'CASCADE'
    });
  };

  return DiaryTag;
}; 